//数据库中用户信息
var access_userInfo = [{username:"feng",password:"123"},{username:"gaoqian",password:"123"}];



//连接上的用户列表
var connectList = [];

//登陆成功的用户列表
var loginList = [];

//房间列表
var roomList = [];

application.onAppStart = function ()
{ 
	logger("\n\n<===========================================>");
	logger("App " + application.name + " start.");
	
	initClientFuncs();
}

application.onConnect = function( client ) 
{
	// Accept the connection.
	application.acceptConnection( client );
	
	connectList.push(client);

	logger("Client "+(client.username?client.username: client.id) + " connect.");

}

application.onDisconnect = function(client)
{
	connectList.splice(connectList.indexOf(client),1);
	
	logger("Client "+(client.username?client.username: client.id)+" disconnect"); 
}

function initClientFuncs()
{
	Client.prototype.loginReq=function(info)
	{
		logger("Client "+info.username+" request login.");
		
		for each(var client in loginList)
		{
			if(client.username == info.username)
			{
				client.call("messageNtf",null,{info:"This account has been in other places."});
				
				logger(client.username+" repeat login. Remove previous client.");
				
				var intervalID = setInterval(function()
				{
					application.disconnect(client); 
					clearInterval(intervalID);
				}, 1000); 
			}
		}
		
		var isLoginSucceed = false;
		for each(var userinfo in access_userInfo)
		{
			if(userinfo.username == info.username && userinfo.password == info.password)
			{
				isLoginSucceed = true;
				break;
			}
		}
		
		if(isLoginSucceed)
		{
			this.username = info.username
			
			logger("Client "+this.username + " login succeed");
			loginList.push(this);
			return {loginSucceed:true,userinfo:{username:this.username}};
		}
		else
			logger("Client "+info.username + " login fail");
		
		return {loginSucceed:false};
	};
	
	Client.prototype.logoutReq = function(info)
	{
		logger("Client "+(this.username?this.username: this.id)+ " request logout.");
			
		loginList.splice(loginList.indexOf(this),1);
		
		return {logoutSucceed:true};
	};
	
	Client.prototype.createroomReq = function(info)
	{
		//check name and numPlayer
		if(!(info.name && info.numPlayer))
		{
			return {creatroomSucceed:true};
		}
		
	};
}





function logger(msg)
{
	var date = new Date();
	msg = "["+date.toLocaleTimeString()+"]" + msg;
	
	trace(msg);
	
	var logFile = new File("log/"+date.toDateString()+".txt"); 
	
	logFile.open("text", "append"); 
	logFile.write(msg+"\n");
	logFile.close();
}